package com.itlong.cloud.operate.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.operate.OperateModuleGetPageDTO;
import com.itlong.cloud.POJO.DTO.operate.OperatePropertySaveDeployDTO;
import com.itlong.cloud.POJO.DTO.operate.OperatePropertyValueSaveDTO;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.POJO.VO.operate.OperateModuleGetPageVO;
import com.itlong.cloud.POJO.VO.operate.OperatePropertyValueGetOneVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.enumerate.CloudElevatorChangeBusinessEnum;
import com.itlong.cloud.enumerate.CloudEntranceChangeBusinessEnum;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.SmartCommunityEnum;
import com.itlong.cloud.operate.dao.IOperatePropertyValueDao;
import com.itlong.cloud.operate.service.IOperatePropertyValueService;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      运营物业增值业务处理接口实现类
 * </desc>
 *
 * @createDate 2019/05/29
 */
@Service
public class OperatePropertyValueServiceImpl implements IOperatePropertyValueService {

    @Autowired
    IOperatePropertyValueDao iOperatePropertyValueDao;

    @Autowired
    MessageSender messageSender;
    /**
     * <desc>
     *      获取分页列表
     * </desc>
     *
     * @param dto
     * @return
     * @author Jiaqi.X
     * @createDate 2019/05/29
     */
    @Override
    public Page<OperateModuleGetPageVO> getPage(OperateModuleGetPageDTO dto) throws Exception {
        //将DTO转换为Map params
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(dto);
        //分页类默认pageSize为20
        Page<OperateModuleGetPageVO> page = new Page<>();
        page.getPage().setPageSize(dto.getPageSize());
        page.getPage().setCurrentPage(dto.getCurrentPage());
        params.put("currentPage",page.getPage().getStartSlip());
        params.put("pageSize",page.getPage().getPageSize());
        //填充返回数据集
        page.setRows(iOperatePropertyValueDao.getPage(params), iOperatePropertyValueDao.getPageCount(params));
        return page;
    }

    /**
     * <desc>
     *      获取单个对象
     * </desc>
     *
     * @param moduleId
     * @return
     * @author Jiaqi.X
     * @createDate 2019/05/29
     */
    @Override
    public OperatePropertyValueGetOneVO getOne(String moduleId,String projectId) {
        OperatePropertyValueGetOneVO vo = iOperatePropertyValueDao.getOne(moduleId,projectId);
        if(vo !=null && StringUtils.isNotBlank(vo.getModuleId())) {
            //获取物业配置
            vo.setArrearsLevels(iOperatePropertyValueDao.getDeploys(moduleId));
        }
        return vo;
    }

    /**
     * <desc>
     *      保存物业增值配置
     * </desc>
     *
     * @param dto
     * @return
     * @author Jiaqi.X
     * @createDate 2019/05/29
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public String save(OperatePropertyValueSaveDTO dto) throws Exception {
        PropertyValuePO po = new PropertyValuePO();
        Integer saveOrUpdate = 1;   //1代表保存 2代表修改
        String propertyValueId = iOperatePropertyValueDao.getPropertyValueIdByProjectId(dto.getProjectId());
        if(StringUtils.isBlank(propertyValueId)){
            po.setPropertyValueId(LogicIdUtil.bussinessId());
            po.setCreateTime(new Date());
        }else{
            po.setPropertyValueId(propertyValueId);
            saveOrUpdate = 2;
            po.setUpdateTime(new Date());
        }
        po.setProjectId(dto.getProjectId());
        po.setDeploy(dto.getLowerHairProperty());
        po.setOpenTempPass(dto.getTempPass());
        po.setOpenTempPassPercent(new BigDecimal(dto.getTempPassDivideInto()));
        if(StringUtils.isNotBlank(dto.getTempPassMoney())) {
            po.setTempPassMoney(new BigDecimal(dto.getTempPassMoney()));
        }
        po.setTempPassOpenTime(dto.getTempOpenTime());
        po.setOpenDeviceType(dto.getOpenDevice());
        po.setStatus(DataStatusEnum.NORMAL.getType());
        //更新项目状态
        iOperatePropertyValueDao.updateProjectStatus(dto.getRuleId(),dto.getPropertyValue(),dto.getProjectId());
        //保存修改信息
        if(saveOrUpdate == 1){
            iOperatePropertyValueDao.save(SqlUtil.durableData(po, PlatformConstants.TABLE_SAVE));
        }else{
            iOperatePropertyValueDao.update(SqlUtil.durableData(po, PlatformConstants.TABLE_UPDATE));
        }
        //保存配置信息
        List<OperatePropertySaveDeployDTO> list = dto.getArrearsLevels();
        for(OperatePropertySaveDeployDTO deploy : list){
            saveOrUpdate = 1;//1代表保存 2代表修改
            PropertyValueDeployPO dp = new PropertyValueDeployPO();
            dp.setPropertyValueDeployId(iOperatePropertyValueDao.getPropertyValueDeployIdByModuleId(po.getPropertyValueId(), deploy.getType()));
            if(StringUtils.isBlank(dp.getPropertyValueDeployId())){
                //保存
                dp.setPropertyValueDeployId(LogicIdUtil.userBusinessId());
                dp.setCreateTime(new Date());
            }else{
                //修改
                dp.setPropertyValueDeployId(dp.getPropertyValueDeployId());
                dp.setUpdateTime(new Date());
                saveOrUpdate = 2;
            }
            dp.setProjectId(dto.getProjectId());
            dp.setPropertyValueId(po.getPropertyValueId());
            dp.setLevel(deploy.getType());
            dp.setDay(deploy.getDay());
            dp.setPointOut(deploy.getPointOut());
            dp.setElevatorDeployLimit(deploy.getElevator());
            dp.setEntranceDeployLimit(deploy.getEntrance());
            dp.setCloudIntercomLimit(deploy.getCloudTalk());
            dp.setPhoneDeployLimit(deploy.getPhone());
            dp.setStatus(DataStatusEnum.NORMAL.getType());
            if(saveOrUpdate == 1){
                //保存
                iOperatePropertyValueDao.save(SqlUtil.durableData(dp,PlatformConstants.TABLE_SAVE));
            }else{
                //修改
                iOperatePropertyValueDao.update(SqlUtil.durableData(dp,PlatformConstants.TABLE_UPDATE));
            }
        }
        //推送设备项目信息
        //云对讲
        JSONObject talkObject = new JSONObject();
        talkObject.put("projectId",dto.getProjectId());
        List<DeviceBusinessChangeLogPO> changeLogPOS = new ArrayList<>();
        changeLogPOS.add(new DeviceBusinessChangeLogPO(SmartCommunityEnum.PUSH_PROJECT, talkObject, dto.getProjectId()));
        JSONObject talkJs = new JSONObject();
        talkJs.put("data", changeLogPOS);
        messageSender.send(
                RabbitMQConstant.RABBITMQ_HANDLE_SMART_COMMUNITY_ORDERS_QUEUE,
                JSON.toJSONString(talkJs),
                RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_EXCHANGE,
                RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_ROUTING_KEY
        );
        //云电梯
        //项目信息变更通知云电梯
        JSONObject elevatorObject = new JSONObject();
        elevatorObject.put("projectId",dto.getProjectId());
        List<DeviceBusinessElevatorChangeLogPO> changeLogPOs = new ArrayList<>();
        changeLogPOs.add(new DeviceBusinessElevatorChangeLogPO(dto.getProjectId(), CloudElevatorChangeBusinessEnum.PUSH_PROJECT,elevatorObject.toJSONString()));
        JSONObject elevatorJs = new JSONObject();
        elevatorJs.put("data",changeLogPOs);
        messageSender.send(
                RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ELEVATOR_CHANGE_BUSINESS_QUEUE,
                JsonUtil.toJSON(elevatorJs),
                RabbitMQConstant.RABBITMQ_CLOUD_ELEVATOR_CHANGE_BUSINESS_EXCHANGE,
                RabbitMQConstant.RABBITMQ_CLOUD_ELEVATOR_CHANGE_BUSINESS_ROUTING_KEY);
        //项目信息变更通知云门禁
        JSONObject entranceObject = new JSONObject();
        entranceObject.put("projectId",dto.getProjectId());
        List<DeviceBusinessEntranceChangeLogPO> changeLogEntrance = new ArrayList<>();
        changeLogEntrance.add(new DeviceBusinessEntranceChangeLogPO(CloudEntranceChangeBusinessEnum.PUSH_PROJECT, entranceObject,dto.getProjectId()));
        JSONObject entranceJs = new JSONObject();
        entranceJs.put("data", changeLogEntrance);
        //发送云门禁指令
        messageSender.send(
                RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ENTRANCE_CHANGE_BUSINESS_QUEUE,
                JSON.toJSONString(entranceJs),
                RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_EXCHANGE,
                RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_ROUTING_KEY
        );
        return po.getPropertyValueId();
    }


}
